<template>
  <div class="week-create">
    <plan-header ref="planHeader" :tableData="tableData" :openDate="$route.query.openDate" :classBtnShow="true" />
    <div class="default" v-if="genDefaultContentShow" :style="{backgroundColor: $store.state.user.baseColor}">
      <el-button @click="genDefaultContent" type="primary" icon="el-icon-search" size="small">填入上一次的内容</el-button>
    </div>
    <div class="item-border" :style="{backgroundColor: $store.state.user.baseColor}">
      <div class="border"></div>
    </div>
    <div class="plan-body" :style="{backgroundColor: $store.state.user.baseColor}">
      <div class="plan-item" v-for="(item,index) in tableBody" :key="index" >
        <div class="item-top">
          <div class="item-name"><span style="color: #0C9776;">课时教案--</span>{{item.name}}</div>
          <div class="item-btn">
            <el-button @click="planTemplate(item)" size="small" type="primary" icon="iconfont icon-05_11hetongmobanshenpichaxun">模板</el-button>
            <el-button @click="planRecord(item)" size="small" type="primary" icon="iconfont icon-biaoshileijihuamoban">撰写记录</el-button>
          </div>
        </div>
        <p class="description">{{item.description}}</p>
        <div class="input" v-if="item.style=='summerNote'" >
          <tinymce :editorRef="item.style+'-'+item.docDefId" :ref="item.style+'-'+item.docDefId" v-model="content[item.style+'-'+item.docDefId]" @contentData="quillChange($event)" :height="200"></tinymce>
        </div>
        <div class="input" v-else >
          <el-input v-model="content[item.style+'-'+item.docDefId]"></el-input>
        </div>
        <div class="item-border" :style="{backgroundColor: $store.state.user.baseColor}">
          <div class="border"></div>
        </div>
      </div>
      <el-button class="save" @click="save" size="small" type="primary" icon="iconfont icon-save" v-loading.fullscreen.lock="loading" element-loading-text="保存中"> 保 存</el-button>
      <el-button v-if="docDataId" class="print" @click="printModalShow" type="primary" icon="el-icon-printer" size="small">打印</el-button>
      <el-button class="seeWeek" @click="seeWeek" type="primary" icon="el-icon-view" size="small">查看周计划</el-button>
      <!-- 打印 -->
      <vxe-modal v-model="printModal" title="预览" height="800" show-zoom resize width="600" show-footer>
        <template #default>
          <weekPlanPrint  id="myPrint" :previewData="printData" :docClassId="docClassId" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
        </template>
      </vxe-modal>
      <!-- 查看周计划 -->
      <vxe-modal v-model="previewShow" title="本周训练计划内容参考" height="500" show-zoom resize width="800" :mask="false" :lockView="false">
        <template #default>
          <weekPreview :previewData="previewData" :currentDay="currentDay" @previewWeekplanChange="previewWeekplanChange" />
        </template>
      </vxe-modal>
      <!-- 撰写记录 -->
      <vxe-modal v-model="planRecordShow" title="撰写记录" height="500" show-zoom resize width="500" :mask="false" :lockView="false">
        <template #default>
          <planRecord :docItemDefId="planRecordCurrentDocItemDefId" :currentStyle="currentStyle"  @getplanRecordName="getplanRecordName" />
        </template>
      </vxe-modal>
      <!-- 模板 -->
      <vxe-modal v-model="templateShow" title="课时训练计划模板" height="80%" show-zoom resize width="800" :mask="false" :lockView="false" @close="templateCloseWatch">
        <template #default>
          <planTemplate ref="planTemplate" :docItemDefId="currentDocItemDefId" :sportId="currentSportId" @getTemplateName="getTemplateName" :empId="empId" @templateClose="templateClose"/>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {classExercisePlan,insertDocData,planSave,updateDocData,getContent,allType,genDefault} from "@/api/plan.js"
  import planHeader from "@/components/plan/planHeader.vue"
  import Tinymce from "@/components/Tinymce";
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  import weekPreview from "@/components/print/weekPreview.vue"
  import planRecord from "@/components/plan/planRecord.vue"
  import planTemplate from "@/components/plan/planTemplate.vue"
  export default {
    components: {
      planHeader,
      Tinymce,
      weekPlanPrint,
      weekPreview,
      planRecord,
      planTemplate
    },
    data() {
      return {
        docClassId: '',
        docDataId: '',
        tableData: {},
        tableBody: [],
        content: {},
        statusId: 1,
        loading: false,
        currentDate: '',
        parentId: '',
        printModal: false,
        printData: {},
        previewShow: false,
        previewData: [],
        currentDay: '',
        planRecordShow: false,
        currentDocItemDefId: '',
        planRecordCurrentDocItemDefId: '',
        currentStyle: '',
        templateShow: false,
        currentSportId: '',
        templateStr: '',
        empId: '',
        genDefaultContentShow: true,
      }
    },
    created() {
      this.docDataId = this.$route.query.docDataId
      this.parentId = this.$route.query.parentId
      this.getPlanData()
    },
    watch: {
      docDataId(val){
        if(val) {
          this.genDefaultContentShow = false
        }
      }
    },
    methods: {
      templateCloseWatch() {
        this.$refs.planTemplate.closeTemplate()
      },
      quillChange({content,key}) {
        this.content[key] = content
      },
      templateClose() {
        this.templateShow = false
      },
      previewWeekplanChange(str) {
        this.content['summerNote-167'] = this.content['summerNote-167']+str
        this.$refs['summerNote-167'][0].setContent(this.content['summerNote-167'])
      },
      getTemplateName(str) {
        let key = this.currentStyle+'-'+this.currentDocItemDefId
        if(this.currentStyle == 'summerNote'){
          this.templateStr = this.content[key]+str
          this.$refs[key][0].setContent(this.templateStr)
        }else{
          str = str.replace(new RegExp("<p>", "gm"), "");
          str = str.replace(new RegExp("</p>", "gm"), "");
          this.templateStr = this.content[key] + str
          this.content[key] = this.templateStr
        }
        this.$message.success('内容已添加到编辑区')
      },
      planTemplate(item) {
        this.currentDocItemDefId = item.docDefId
        this.currentStyle = item.style
        this.currentSportId = this.$refs.planHeader.planForm.sportId
        this.empId = this.$refs.planHeader.planForm.empId
        this.templateShow = true
      },
      getplanRecordName(item) {
        let key = this.currentStyle+'-'+item.docItemDefId
        this.content[key] = ''
        if(this.currentStyle == 'summerNote'){
          // this.content[key] = item.content
          this.$refs[key][0].setContent(item.content)
        }else{
          this.content[key] = item.val
        }
      },
      planRecord(item) {
        this.planRecordCurrentDocItemDefId = item.docDefId
        this.currentStyle = item.style
        this.planRecordShow = true
      },
      // 填入上一次
      genDefaultContent() {
        let sportId = this.$refs.planHeader.planForm.sportId
        let openDate = this.$route.query.openDate+ ' 00:00:00'
        genDefault({sportId:sportId,openDate:openDate}).then(res=>{
          if(res.code === 200) {
            if(res.data.length==0) return
            for (let key in this.content) {
              let arr = key.split('-')
              let docDefId = arr[1]
              res.data.forEach(item=>{
                if(docDefId == item.docItemDefId){
                  if(arr[0] == 'summerNote'){
                    // this.content[key] = item.content
                    this.$refs[key][0].setContent(item.content)
                  }else{
                    this.content[key] = item.val
                  }
                }
              })
            }
            this.genDefaultContentShow = false
          }else{
            this.genDefaultContentShow = false
          }
        })
      },
      // 查看周计划
      seeWeek() {
        allType({docDataId:this.parentId,docClassId:33}).then(res=>{
          if(res.code === 200) {
            let obj = res.data
            if(this.$route.query.openDate){
              this.currentDate = this.$route.query.openDate
            }else{
              this.currentDate = this.tableData.tableHeader[1].closeDate
            }
            this.previewData = obj[Object.keys(obj)[0]]
            let date = new Date(this.currentDate)
            this.currentDay = date.getDay()
            this.previewShow = true
          }else{
            this.$message.error(res.message)
          }
        })
      },
      // 打印
      printEvent() {
        const divEl = document.getElementById('myPrint')
        const printStyle = `
          #myPrint{
            color: #000;
          }
          p{
            margin: 4px 0;
          }
        `
        this.$XPrint({
          sheetName: '',
          style: printStyle,
          content: divEl.innerHTML
        })
      },
      printModalShow() {
        allType({docDataId:this.docDataId,docClassId:this.docClassId}).then(res=>{
          if(res.code === 200) {
            this.printData = res.data
            this.printModal = true
          }else{
            this.$message.error(res.message)
          }
        })
      },
      // 保存
      save() {
        this.loading = true
        let headerData = this.$refs.planHeader.planForm
        let doubleDate = this.$refs.planHeader.doubleDate
        let json = {
          openDate: doubleDate[0] + ' 00:00:00',
          closeDate: doubleDate[1] + ' 00:00:00',
          name: headerData.name,
          empId: headerData.empId,
          docDataEmp: headerData.docDataEmpId.join(','),
          createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD') + ' 00:00:00',
          docClassId: this.docClassId,
          statusId: 1,
        }
        if(headerData.sportId) json.sportId = headerData.sportId
        if(headerData.sportItemId) json.sportItemId = headerData.sportItemId
        if(this.docDataId){
          json['docDataId'] = this.docDataId
          // 先修改头
          updateDocData(json).then(res=>{
            if(res.code === 200){
              // 再修改身体
              this.planBodySave(headerData)
            }else{
              this.loading = false
              this.$message.error(res.message)
            }
          })
        }else{
          json['parentId'] = this.parentId
          // 先保存头
          insertDocData(json).then(res=>{
            if(res.code === 200) {
              this.docDataId = res.data.docDataId
              // 再保存身体
              this.planBodySave(headerData)
            }else{
              this.loading = false
              this.$message.error(res.message)
            }
          })
        }
        this.loading = false
      },
      planBodySave(headerData) {
        let data = []
        for (let key in this.content) {
          let type = key.split('-')
          if(this.content[key]){
            this.content[key] = this.content[key].replace(/\n/g,"");
          }
          if(type[0] == 'summerNote'){
            data.push({
              content: this.content[key],
              createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD'),
              docClassId: this.docClassId,
              docDataId: this.docDataId,
              docItemDefId: type[1],
              docItemTypeId: "1",
              empId: headerData.empId,
              statusId: this.statusId,
              val: ""
            })
          }else{
            data.push({
              content: "",
              createDate: this.$moment(headerData.createDate).format('YYYY-MM-DD'),
              docClassId: this.docClassId,
              docDataId: this.docDataId,
              docItemDefId: type[1],
              docItemTypeId: "1",
              empId: headerData.empId,
              statusId: this.statusId,
              val: this.content[key],
            })
          }
        }
        planSave(data).then(res=>{
          if(res.code === 200){
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 0,
              position: 'bottom-right'
            });
            this.$message.success('数据保存成功.!')
            this.$router.push({
                query:{
                    docDataId: this.docDataId,
                    parentId: this.parentId
                }
            })
          }else{
            this.$message.error(res.message)
          }
          this.loading = false
        })
      },
      getPlanContent() {
        getContent({docDataId:this.docDataId}).then(res=>{
          if(res.code === 200) {
            this.tableData = res.data
          }else{
            this.$message.error(res.message)
          }
        })
      },
      getPlanData() {
        if(this.docDataId) {
          getContent({docDataId:this.docDataId}).then(res=>{
            if(res.code === 200) {
              this.tableData = res.data
              this.tableData.parentId = this.parentId
              this.docClassId = res.data.planTypeId
              this.tableBody = res.data.tableBody
              this.tableBody.forEach(item=>{
                if(item.style == 'summerNote') {
                  this.$set(this.content,item.style+'-'+item.docDefId,item.content)
                }else{
                  this.$set(this.content,item.style+'-'+item.docDefId,item.val)
                }
              })
            }else{
              this.$message.error(res.message)
            }
          })
        }else{
          classExercisePlan().then(res=>{
            if(res.code === 200) {
              this.tableData = res.data
              this.tableData.parentId = this.parentId
              this.docClassId = res.data.planTypeId
              this.tableBody = res.data.tableBody
              this.tableBody.forEach(item=>{
                this.$set(this.content,item.style+'-'+item.docDefId,'')
              })
            }else{
              this.$message.error(res.message)
            }
          })
        }
      }
    },
    beforeDestroy() {
      this.$notify.closeAll()
    }
  }
</script>

<style lang="scss" scoped>
  .week-create{
    .default{
      background-color: #FFFFFF;
      text-align: center;
    }
    .plan-body{
      background-color: #FFFFFF;

      .plan-item{
        width: 100%;
        padding: 10px 0;
        .item-top{
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 250px;

          .item-name{
            font-size: 120%;
          }
        }
        .description{
          padding: 0 250px;
        }
        .input{
          padding: 10px 250px;
        }
      }
    }
    .item-border{
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #FFFFFF;
      .border{
        height: 1px;
        width: 90%;
        background-image: linear-gradient(to right, #fff , #c7c7c7, #fff );
        margin: 20px auto;
      }
    }

    .save{
      position: fixed;
      bottom: 50px;
      right: 50px;
    }
    .print{
      position: fixed;
      top: 150px;
      right: 50px;
    }
    .seeWeek{
      position: fixed;
      top: 50%;
      right: 50px;
    }
  }

</style>
